<template>
  <div class="container">
    <!-- 图表容器 -->
    <div class="wrap">
      <div ref="chartContainer1" class="chart"></div>
      <div ref="chartContainer2" class="chart"></div>
    </div>

    <div @click="onClick" class="visible-btn">AI数据分析</div>

    <div class="wrap">
      <div ref="chartContainer3" class="chart"></div>
      <!-- 信息面板 -->
      <div class="info-panel">
        <img
          src="../images/13118080665_358104652.png"
          alt="Motor Image"
          class="motor-image"
        />
        <div class="info-text">
          <span class="tip">电机剩余寿命:</span>
          <span class="remaining-life">{{ message }} 小时</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { markRaw } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import { ElMessageBox } from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
// 数值过滤函数，保留两位小数
export function numFilter(value) {
  return Number(value).toFixed(2);
}

export default {
  data() {
    return {
      xData1: [], // 更新时间
      xData2: [], // 更新时间
      xData3: [], // 更新时间
      speedData: [], // 速度
      placeData: [], // 位移
      addspeedData: [], // 温度
      randomTemp: 2, // 新增：温度波动范围，默认值为2
      message: 4002.4,
      isMessageBoxShow: false,
      isOn: false,
    };
  },
  created() {
    // 每2秒获取一次剩余寿命
    let timeTicket = setInterval(() => {
      this.getRlife();
    }, 2000);
  },
  mounted() {
    // 初始化图表
    this.initChart1();
    this.initChart2();
    this.initChart3();
    // 添加窗口大小改变事件监听器
    window.addEventListener("resize", this.resizeCharts);
  },
  beforeDestroy() {
    // 移除窗口大小改变事件监听器
    window.removeEventListener("resize", this.resizeCharts);
  },
  methods: {
    // 获取剩余寿命
    getRlife() {
      // try {
      //   axios.get("/v1/test/getrlife", { params: { code: 1 } }).then((res) => {
      //     this.message = numFilter(res.data.data);
      //   });
      // } catch (error) {
      //   console.error(error);
      // }
    },
    // 初始化图表1
    initChart1() {
      this.chart1 = echarts.init(this.$refs.chartContainer1);
      this.chart1.setOption(
        this.getChartOption("振动速度折线图", "速度", "red")
      );
      this.fetchAndSetData(
        this.chart1,
        "wz_velocity",
        this.speedData,
        this.xData1
      );
      this.startUpdatingData(
        this.chart1,
        "wz_velocity",
        this.speedData,
        this.xData1
      );
    },
    // 初始化图表2
    initChart2() {
      this.chart2 = echarts.init(this.$refs.chartContainer2);
      this.chart2.setOption(
        this.getChartOption("振动位移折线图", "位移", "green")
      );
      this.fetchAndSetData(
        this.chart2,
        "wz_displacement",
        this.placeData,
        this.xData2
      );
      this.startUpdatingData(
        this.chart2,
        "wz_displacement",
        this.placeData,
        this.xData2
      );
    },
    // 初始化图表3
    initChart3() {
      this.chart3 = echarts.init(this.$refs.chartContainer3);
      this.chart3.setOption(
        this.getChartOption("电机温度折线图", "温度", "blue")
      );
      this.fetchAndSetData(
        this.chart3,
        "wz_addSPeed",
        this.addspeedData,
        this.xData3
      );
      this.startUpdatingData(
        this.chart3,
        "wz_addSPeed",
        this.addspeedData,
        this.xData3
      );
    },
    // 获取图表配置选项
    getChartOption(titleText, seriesName, color) {
      return {
        title: { text: titleText },
        legend: {
          data: [seriesName],
          backgroundColor: "#f5f5f5",
          borderColor: "#ccc",
          borderWidth: 1,
        },
        xAxis: {
          data: [],
          splitLine: { show: true, lineStyle: { type: "dashed" } },
          axisLabel: {
            rotate: 0, // 增加标签旋转角度，防止数据挤在一起
            fontSize: 10, // 调整字体大小
            margin: 10, // 增加标签与轴的距离
          },
        },
        yAxis: {
          type: "value",
          splitLine: { show: true, lineStyle: { type: "dashed" } },
          axisLabel: {
            fontSize: 12, // 调整字体大小
            margin: 10, // 增加标签与轴的距离
          },
        },
        grid: {
          left: "5%", // 调整图表左边距
          right: "5%", // 调整图表右边距
          bottom: "5%", // 增加底部边距，为旋转的标签留出空间
          containLabel: true, // 确保标签不会被裁剪
        },
        series: [
          {
            name: seriesName,
            type: "line",
            smooth: true, // 启用平滑效果
            data: [],
            lineStyle: { color, width: 2 }, // 增加线条宽度
            itemStyle: { color, borderColor: color, borderWidth: 1 }, // 增加数据点边框
            label: {
              show: true,
              position: "top",
              textStyle: { fontSize: 16, color: "#333" },
            },
          },
        ],
      };
    },
    // 获取并设置数据
    fetchAndSetData(chart, dataKey, dataArray, xData) {
      let data = {
        updatetime: this.formatTime(new Date()),
        wz_velocity: 0.4,
        wz_addSPeed: 60,
        wz_displacement: 0.4 * 7.92,
      };

      // 模拟数据
      dataArray.push(data[dataKey]);
      xData.push(data.updatetime);

      chart.setOption({
        xAxis: { data: xData },
        series: [{ data: dataArray }],
      });
    },
    // 开始更新数据
    startUpdatingData(chart, dataKey, dataArray, xData, n = 7) {
      let index = 0;
      let timeTicket = setInterval(() => {
        const randomTemp = Math.random() * 2 - 1; // 温度随机波动值生成-1到1之间的随机数

        let dataPoint = {
          updatetime: this.formatTime(new Date()),
          wz_velocity: (0.4 + (Math.random() - 0.5) * 0.06).toFixed(3),
          wz_addSPeed: (60 + randomTemp).toFixed(1),
          wz_displacement: (
            (0.4 + (Math.random() - 0.5) * 0.06) *
            7.92
          ).toFixed(3),
        };
        if (this.isOn) {
          const increaseStep = (0.6 - 0.4) / n;
          const randomFluctuation = (Math.random() - 0.5) * 0.06; // 生成 -0.03 到 0.03 之间的随机数

          const increaseStep1 = (60 - 50) / n;
          const increaseStep2 = (8100 - 4002.4) / n;
          if (index <= n) {
            index++;
            dataPoint.wz_velocity = (
              Math.min(0.4 + increaseStep * index, 0.6) + randomFluctuation
            ).toFixed(3);
            dataPoint.wz_displacement = (dataPoint.wz_velocity * 7.92).toFixed(
              3
            );
            dataPoint.wz_addSPeed = (
              Math.max(60 - increaseStep1 * index, 50) + randomTemp
            ).toFixed(3);

            this.message = Math.min(
              4002.4 + increaseStep2 * index,
              7988.5
            ).toFixed(1);
          } else {
            dataPoint.wz_velocity = (0.6 + randomFluctuation).toFixed(3);
            dataPoint.wz_displacement = (dataPoint.wz_velocity * 7.92).toFixed(
              3
            );
            dataPoint.wz_addSPeed = (50 + randomTemp).toFixed(1);
            this.message = 7988.5;
          }
        }

        dataArray.push(dataPoint[dataKey]);
        xData.push(dataPoint.updatetime);
        if (dataArray.length > 10) {
          dataArray.shift();
          xData.shift();
        }
        chart.setOption({
          xAxis: { data: xData },
          series: [{ data: dataArray }],
        });
      }, 1000);
    },
    // 调整图表大小
    resizeCharts() {
      this.chart1.resize();
      this.chart2.resize();
      this.chart3.resize();
    },
    // 格式化时间
    formatTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    onClick() {
      this.isOn = true;
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 0; /* 删除原有 padding */
  margin: 0; /* 删除原有 margin */
  height: 100vh; /* 设置容器高度为视口高度 */
  padding: 30px;
  box-sizing: border-box;
}
.wrap {
  width: 100%;
  display: flex;
  gap: 20px;
  height: 300px;
}
.chart {
  flex: 1;
  height: 300px; /* 固定高度为300px */
  margin: 0;
  border: 1px solid #ddd; /* 添加边框以区分图表区域 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.info-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 300px;
}

.motor-image {
  width: 350px;
  height: auto;
  margin-right: 20px;
}
.tip {
  font-size: 20px;
}
.info-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.remaining-life {
  font-size: 60px;
  font-weight: 900;
  color: #0000ff;
  margin-top: 10px;
}
.visible-btn {
  text-align: center;
  width: 200px;
  height: 40px;
  color: #fcfbfb;
}
</style>